package com.heima.app.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2022/1/1 23:32
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 全局过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 判断是否是登录的请求
        String path = request.getURI().getPath();
        if (path.contains("/login_auth")){
            // 如果是登录就放行
            return chain.filter(exchange);
        }

        // 如果是其他请求就拦截，验证是否已经登录
        // 获取token
        String token = request.getHeaders().getFirst("token");

        // token为空返回，并且拦截
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        // 判断token是否正确，抛异常不正确，反之亦然
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            // 响应未登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 返回值类型
        }

    }

    // 过滤器顺序
    @Override
    public int getOrder() {
        return 0;
    }
}
